package com.road.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.road.model.OperateImage;
import com.road.model.admin.vo.UserVo;
import com.road.model.easyui.PageInfo;
import com.road.model.entity.Role;
import com.road.model.entity.User;
import com.road.service.UserService;
import com.road.utils.MessageModel;

/**
 * @description：用户管理
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	private static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Value(value = "${upload.path}")
	private String path;

	/**
	 * 用户管理页
	 *
	 * @return
	 */
	@RequestMapping(value = "/manager", method = RequestMethod.GET)
	public String manager() {
		return "/admin/user";
	}

	/**
	 * 用户管理列表
	 *
	 * @param userVo
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/dataGrid", method = RequestMethod.POST)
	@ResponseBody
	public PageInfo<User> dataGrid(UserVo userVo, Integer page, Integer rows, String sort, String order) {
		PageInfo<User> pageInfo = new PageInfo<User>(page, rows);
		Map<String, Object> condition = Maps.newHashMap();

		if (StringUtils.isNoneBlank(userVo.getName())) {
			condition.put("name", userVo.getName());
		}
		if (userVo.getOrganizationId() != null) {
			condition.put("organizationId", userVo.getOrganizationId());
		}
		if (userVo.getCreateDateStart() != null) {
			condition.put("startTime", userVo.getCreateDateStart());
		}
		if (userVo.getCreateDateEnd() != null) {
			condition.put("endTime", userVo.getCreateDateEnd());
		}
		if (StringUtils.isNotBlank(sort)) {
			if ("DESC".equalsIgnoreCase(sort)) {
				condition.put("sort", -1);
			} else {
				condition.put("sort", 1);
			}
		}
		if (StringUtils.isNotBlank(order)) {
			condition.put("order", order);
		}
		pageInfo.setCondition(condition);
		userService.findDataGrid(pageInfo);
		return pageInfo;
	}

	/**
	 * 添加用户页
	 *
	 * @return
	 */
	@RequestMapping(value = "/addPage", method = RequestMethod.GET)
	public String addPage() {
		return "/admin/userAdd";
	}

	/**
	 * 添加用户
	 *
	 * @param userVo
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public MessageModel add(UserVo userVo) {
		MessageModel result = new MessageModel();
		User u = userService.findUserByLoginName(userVo.getLoginName());
		if (u != null) {
			result.setMsg("用户名已存在!");
			return result;
		}
		try {
			userVo.setPassword(DigestUtils.md5Hex(userVo.getPassword()));
			userService.addUser(userVo);
			result.setSuccess(true);
			result.setMsg("添加成功");
			return result;
		} catch (RuntimeException e) {
			LOGGER.error("添加用户失败：{}", e);
			result.setMsg(e.getMessage());
			return result;
		}
	}

	/**
	 * 编辑用户页
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/editPage")
	public String editPage(Long id, Model model) {
		UserVo userVo = userService.findUserVoById(id);
		List<Role> rolesList = userVo.getRolesList();
		List<Long> ids = Lists.newArrayList();
		for (Role role : rolesList) {
			ids.add(role.getId());
		}
		model.addAttribute("roleIds", ids);
		model.addAttribute("user", userVo);
		return "/admin/userEdit";
	}

	/**
	 * 编辑用户
	 *
	 * @param userVo
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public MessageModel edit(UserVo userVo) {
		MessageModel result = new MessageModel();
		User user = userService.findUserByLoginName(userVo.getLoginName());
		if (user != null && user.getId() != userVo.getId()) {
			result.setMsg("用户名已存在!");
			return result;
		}
		try {
			userVo.setPassword(DigestUtils.md5Hex(userVo.getPassword()));
			userService.updateUser(userVo);
			result.setSuccess(true);
			result.setMsg("修改成功！");
			return result;
		} catch (RuntimeException e) {
			LOGGER.error("修改用户失败：{}", e);
			result.setMsg(e.getMessage());
			return result;
		}
	}

	/**
	 * 修改密码页
	 *
	 * @return
	 */
	@RequestMapping(value = "/editPwdPage", method = RequestMethod.GET)
	public String editPwdPage() {
		return "/admin/userEditPwd";
	}

	/**
	 * 修改密码
	 *
	 * @param request
	 * @param oldPwd
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/editUserPwd")
	@ResponseBody
	public MessageModel editUserPwd(HttpServletRequest request, String oldPwd, String pwd) {
		MessageModel result = new MessageModel();
		if (!getCurrentUser().getPassword().equals(DigestUtils.md5Hex(oldPwd))) {
			result.setMsg("老密码不正确!");
			return result;
		}

		try {
			userService.updateUserPwdById(getUserId(), DigestUtils.md5Hex(pwd));
			result.setSuccess(true);
			result.setMsg("密码修改成功！");
			return result;
		} catch (Exception e) {
			LOGGER.error("修改密码失败：{}", e);
			result.setMsg(e.getMessage());
			return result;
		}
	}

	/**
	 * 删除用户
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public MessageModel delete(Long id) {
		MessageModel result = new MessageModel();
		try {
			userService.deleteUserById(id);
			result.setMsg("删除成功！");
			result.setSuccess(true);
			return result;
		} catch (RuntimeException e) {
			LOGGER.error("删除用户失败：{}", e);
			result.setMsg(e.getMessage());
			return result;
		}
	}

	/**
	 * 
	 * @Name: toUpload
	 * @Description:用户头像上传
	 * @Author: WeiHui.Zhang
	 * @Version: V1.00
	 * @Date: 2016年4月8日下午4:49:39
	 * @return
	 * @Return: String
	 */
	@RequestMapping("avatar")
	public String toUpload() {
		return "system/user/avatar";
	}

	@RequestMapping("upload")
	@ResponseBody
	public Map<Boolean, String> uploadAvatar(@RequestParam MultipartFile multipartFile, HttpServletRequest request) {
		String fileName = multipartFile.getOriginalFilename();
		File target = new File(path + fileName);

		if (!target.exists()) {
			target.mkdirs();
		}
		try {
			multipartFile.transferTo(target);

			// 裁剪图片
			String thumbFileName = System.currentTimeMillis() + ".jpg";
			String thumbFilePath = path + thumbFileName;
			JSONObject object = JSON.parseObject(request.getParameter("avatar_data"));
			OperateImage o = new OperateImage((int) Float.parseFloat(object.get("x").toString()),
					(int) Float.parseFloat(object.get("y").toString()),
					(int) Float.parseFloat(object.get("width").toString()),
					(int) Float.parseFloat(object.get("height").toString()));
			o.setSrcPath(path + fileName);// 输入图片地址
			o.setSubPath(thumbFilePath);// 输出图片地址
			o.cut();
			Map<Boolean, String> result = Maps.newHashMap();
			result.put(true, thumbFilePath);
			return result;
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
